<?php

namespace app\controllers;

use app\components\WebController;
use app\models\User;
use app\models\UserPlatform;
use yii;
use yii\authclient\OAuth2;

class AuthController extends WebController {

    public $layout = 'auth';

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }
        if (!Yii::$app->user->getIsGuest()) {
            $this->goBack(['user/']);
            return FALSE;
        }
        return TRUE;
    }

    public function actionRegister() {
        $model = new User();
        $model->setScenario('register');
        if ($model->load($this->post())) {
            return $model->registerByPhone();
        }
        $this->view->title = '注册';
        return $this->render(compact('model'));
    }

    public function actionLogin() {
        $model = new User();
        $model->setScenario('login');
        if ($model->load($this->post())) {
            return $model->loginByPhone();
        }
        $this->view->title = '登录';
        return $this->render(compact('model'));
    }

    public function actionResetPwd() {
        $model = new User();
        $model->setScenario('register');
        if ($model->load($this->post())) {
            $res = $model->resetPwd();
            $res['redirect'] = yii\helpers\Url::to(['auth/login']);
            return $res;
        }
        $this->view->title = '忘记密码';
        return $this->render(compact('model'));
    }

    public function actions() {
        $actions = parent::actions();
        $actions['weixin'] = [
            'class' => 'yii\authclient\AuthAction',
            'successCallback' => [$this, 'successCallback'],
            'authclient' => 'weixin',
        ];
        return $actions;
    }

    public function successCallback(OAuth2 $client) {
        $userInfo = $client->getUserAttributes();
        $id = $client->getId();

        $types = UserPlatform::$typeNames;
        if (!isset($types[$id])) {
            return $this->error("oauth $id");
        }

        $userPlatform = new UserPlatform();
        $res = $userPlatform->savePlatform($userInfo, $types[$id]);
        if ($res['code'] != 0) {
            return $res;
        }

        return $this->redirect(['user/identity']);
    }
}
